<?php

/**
 * alltosun.com 用户控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址:   http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
 * $Date: 2014-11-17 下午6:41:46 $
 * $Id$
 */
class Action
{
    private $per_page = 100;

    /**
     * 显示用户列表
     */
    public function index() {

        $page_no = $status = $only_dealer = $dealer_level = $assistant_user_id = $test = $role_id = $role_type = $is_advenced = $search_filter = $is_bbcoin_enable = $is_invoice = null;

        extract(URLTracker::init(array(
            'page' => 1,
            'status' => 1,
            'role_type' => -1,
            'assistant_user_id' => 0,
            // 'role_id' => 0,
            'is_advenced' => 0,
            'is_bbcoin_enable' => -1,
            'is_invoice' => -1,
            'search_filter' => array()
        )));

        // 拼装搜索条件
        $filter = array();

        // 拼装查询条件
        $query_string = 'page_no=' .
                        $page_no .
                        '&status=' .
                        $status .
                        '&only_dealer=' .
                        $only_dealer .
                        '&dealer_level=' .
                        $dealer_level .
                        '&assistant_user_id=' .
                        $assistant_user_id;
        // 过滤提交的参数
        $search_filter = array_map('trim', $search_filter);
        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'] . ' 00:00:00';
            $query_string .= '&search_filter[start_date]=' . $search_filter['start_date'];
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'] . ' 23:59:59';
            $query_string .= '&search_filter[end_date]=' . $search_filter['end_date'];
        }

        if (isset($search_filter['realname']) && $search_filter['realname']) {
            $filter['`realname` LIKE '] = '%' . $search_filter['realname'] . '%';
            $query_string .= '&search_filter[realname]=' . $search_filter['realname'];
        }

        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $get_way = user_helper::get_user_login_way($search_filter['user_name']);
            switch ($get_way) {
                case '1':
                    $filter['`email` LIKE '] = '%' . $search_filter['user_name'] . '%';
                    break;

                case '2':
                    $filter['`mobile` LIKE '] = '%' . $search_filter['user_name'] . '%';
                    break;

                default:
                    $filter['`user_name` LIKE '] = '%' . $search_filter['user_name'] . '%';
                    break;
            }
            $query_string .= '&search_filter[user_name]=' . $search_filter['user_name'];
        }

        // 角色过滤
        if (isset($search_filter['role_id']) && $search_filter['role_id']) {
            $user_ids = user_helper::get_role_user_ids($search_filter['role_id'], '');
            if ($user_ids) {
                $filter['id'] = $user_ids;
            }
            $query_string .= '&search_filter[role_id]=' . $search_filter['role_id'];
        }

        // 角色过滤
        if ($is_invoice > -1) {
            $filter['is_invoice'] = $is_invoice;
        }

        $filter['is_enable'] = 1;

        // 强制合伙人
        if ($is_bbcoin_enable > -1) {
            $filter['dealer_level > '] = 0;
            $filter['is_bbcoin_enable'] = $is_bbcoin_enable == 1 ? 1 : 0;
            if (!in_array($role_type, array(0, 1, 2))) {
                $role_type = 0;
                URLTracker::set('role_type', 0, true);
            }
        }

        switch ($role_type) {
            case -1:
                // 全部
                break;
            case 0:
                // 只看合伙人
                $filter['dealer_level > '] = 0;
                break;
            case 1:
                // 一级合伙人
                $filter['dealer_level'] = 1;
                break;
            case 2:
                // 二级合伙人
                $filter['dealer_level'] = 2;
                break;
            case 3:
                // 门店
                $filter['store_parent_id > '] = 0;
                break;
            case 5:
                // 其他
                $filter['dealer_level'] = 0;
                $filter['store_parent_id'] = 0;
                break;
        }

        // 获取此助理的所有合伙人
        if ($assistant_user_id) {
            $filter['assistant_user_id'] = $assistant_user_id;
        }

        $filter['status'] = $status;

        $user_list = array();
        $user_count = _model('user')->getTotal(enable_filter($filter));
        if ($user_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($user_count)) {
                Response::assign('pager', $pager);
            }

            $user_list = _model('user')->getList(enable_filter($filter), ' ORDER BY `id` DESC ' .
                                                                         $pager->getLimit($page_no));
        }

        if ($user_list) {
            foreach ($user_list as $k => $v) {
                if ($v['parent_id'] > 0) {
                    $parent_user_info = _uri('user', $v['parent_id']);
                    $user_list[$k]['parent_user_name'] = $parent_user_info['user_name'];
                }

                // 获取用户的角色id
                $role_id = user_helper::get_user_role_id($v['id']);
                $role_arr = user_config::$role_arr;
                $user_list[$k]['role_id'] = $role_id;
                $role_info = user_helper::get_user_role_info($role_id);
                $user_list[$k]['role_type'] = @$role_info['title'];

                if ($role_id == user_config::MARKETING) {
                    $user_marketing_info = _uri('user_marketing', array('marketing_id' => $v['id']));
                    $dealer_info = user_helper::get_user_info($user_marketing_info['agency_id']);
                    $user_list[$k]['dealer_info'] = $dealer_info;
                }

            }
        }

        /**
         * 获取助理列表
         */
        // 助理id是21
        $user_ids = user_helper::get_role_user_ids(user_config::ASSISTANT);
        if ($user_ids) {
            foreach ($user_ids as $k => $v) {
                $user_ids[$k] = user_helper::get_user_info($v);
            }
        }

        Response::assign('assistant_list', $user_ids);
        Response::assign('assistant_user_id', $assistant_user_id);
        Response::assign('only_dealer', $only_dealer);
        Response::assign('dealer_level', $dealer_level);
        Response::assign('user_list', $user_list);
        Response::assign('status', $status);
        Response::assign('role_list', user_config::$role_arr);
        Response::assign('search_filter', $search_filter);
        Response::assign('query_string', base64_encode($query_string));
        Response::assign('is_advenced', $is_advenced);
        Response::display('admin/user_list.html');
    }

    /**
     * 显示用户列表
     */
    public function dealer() {

        $page_no = $status = $only_dealer = $dealer_level = $assistant_user_id = $test = $role_id = $role_type = $is_advenced = $search_filter = $is_bbcoin_enable = $is_invoice = null;

        extract(URLTracker::init(array(
            'page' => 1,
            'status' => 1,
            'role_type' => -1,
            'assistant_user_id' => 0,
            'is_bbcoin_enable' => -1,
            'is_invoice' => -1,
            'search_filter' => array()
        )));

        // 拼装搜索条件
        $filter = array();

        // 拼装查询条件
        $query_string = 'page_no=' .
                        $page_no .
                        '&status=' .
                        $status .
                        '&only_dealer=' .
                        $only_dealer .
                        '&dealer_level=' .
                        $dealer_level;

        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'] . ' 00:00:00';
            $query_string .= '&search_filter[start_date]=' . $search_filter['start_date'];
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'] . ' 23:59:59';
            $query_string .= '&search_filter[end_date]=' . $search_filter['end_date'];
        }

        if (isset($search_filter['realname']) && $search_filter['realname']) {
            $filter['realname'] = $search_filter['realname'];
            $query_string .= '&search_filter[realname]=' . $search_filter['realname'];
        }

        // 角色过滤
        if ($is_invoice > -1) {
            $filter['is_invoice'] = $is_invoice;
        }

        $filter['is_enable'] = 1;
        $filter['dealer_level > '] = 0;

        // 强制合伙人
        if ($is_bbcoin_enable > -1) {
            $filter['is_bbcoin_enable'] = $is_bbcoin_enable == 1 ? 1 : 0;
        }

        switch ($role_type) {
            case 0:
                // 只看合伙人
                $filter['dealer_level > '] = 0;
                break;
            case 1:
                // 一级合伙人
                $filter['dealer_level'] = 1;
                break;
            case 2:
                // 二级合伙人
                $filter['dealer_level'] = 2;
                break;
        }

        $filter['status'] = $status;

        $user_list = array();
        $user_count = _model('user')->getTotal(enable_filter($filter));
        if ($user_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($user_count)) {
                Response::assign('pager', $pager);
            }

            $user_list = _model('user')->getList(enable_filter($filter), ' ORDER BY `id` DESC ' .
                                                                         $pager->getLimit($page_no));
        }

        if ($user_list) {
            foreach ($user_list as $k => $v) {
                if ($v['parent_id'] > 0) {
                    $parent_user_info = _uri('user', $v['parent_id']);
                    $user_list[$k]['parent_user_name'] = $parent_user_info['user_name'];
                }

                // 获取用户的角色id
                if ($v['dealer_level'] == 1) {
                    $user_list[$k]['role_type'] = '1级合伙人';
                }
                if ($v['dealer_level'] == 2) {
                    $user_list[$k]['role_type'] = '2级合伙人';
                }

                $user_list[$k]['role_id'] = user_config::AGENCY;
            }
        }

        Response::assign('assistant_user_id', $assistant_user_id);
        Response::assign('only_dealer', $only_dealer);
        Response::assign('dealer_level', $dealer_level);
        Response::assign('user_list', $user_list);
        Response::assign('status', $status);
        Response::assign('search_filter', $search_filter);
        Response::assign('query_string', base64_encode($query_string));
        Response::display('admin/dealer_list.html');
    }

    /**
     * 添加用户
     */
    public function add() {
        $role_list = _model('role')->getList(array(1 => 1));
        // 获取父级合伙人列表
        $filter = array();
        $filter['dealer_level'] = 1;
        $filter['parent_id'] = 0;
        $filter['status'] = 1;
        $father_dealer_list = _model('user')->getList($filter, 'ORDER BY `id` DESC');

        /**
         * 获取助理列表 (@todo 多个合伙人是否允许共用同一个助理?)
         */
        // 助理id是21
        $user_ids = array();
        $user_ids = user_helper::get_role_user_ids(user_config::ASSISTANT);
        if ($user_ids) {
            foreach ($user_ids as $k => $v) {
                $user_ids[$k] = user_helper::get_user_info($v);
            }
        }

        Response::assign('assistant_list', $user_ids);
        Response::assign('role_list', $role_list);
        Response::assign('father_dealer_list', $father_dealer_list);
        Response::display('admin/add.html');
    }

    /**
     * 添加合伙人
     */
    public function add_dealer() {
        $role_list = _model('role')->getList(array(1 => 1));
        // 获取父级合伙人列表
        $filter = array();
        $filter['dealer_level'] = 1;
        $filter['parent_id'] = 0;
        $filter['status'] = 1;
        $father_dealer_list = _model('user')->getList($filter, 'ORDER BY `id` DESC');

        /**
         * 获取助理列表 (@todo 多个合伙人是否允许共用同一个助理?)
         */
        // 助理id是21
        $user_ids = array();
        $user_ids = user_helper::get_role_user_ids(user_config::ASSISTANT);
        if ($user_ids) {
            foreach ($user_ids as $k => $v) {
                $user_ids[$k] = user_helper::get_user_info($v);
            }
        }

        Response::assign('assistant_list', $user_ids);
        Response::assign('role', user_config::$role_arr[user_config::AGENCY]);
        Response::assign('role_id', user_config::AGENCY);
        Response::assign('role_list', $role_list);
        Response::assign('father_dealer_list', $father_dealer_list);
        Response::display('admin/add_dealer.html');
    }

    /**
     * 添加管理员
     */
    public function add_admin() {
        Response::assign('role', user_config::$role_arr[user_config::ADMIN]);
        Response::assign('role_id', user_config::ADMIN);
        Response::display('admin/add_user.html');
    }

    /**
     * 添加售后管理员
     */
    public function add_sale_manager() {
        Response::assign('role', '售后管理员');
        Response::assign('role_id', 2);
        Response::display('admin/add_user.html');
    }

    /**
     * 添加财务管理
     */
    public function add_financial_management() {
        Response::assign('role', user_config::$role_arr[user_config::FINANCIAL_MANAGEMENT]);
        Response::assign('role_id', user_config::FINANCIAL_MANAGEMENT);
        Response::display('admin/add_user.html');
    }

    /**
     * 添加助理
     */
    public function add_assistant() {
        Response::assign('role', user_config::$role_arr[user_config::ASSISTANT]);
        Response::assign('role_id', user_config::ASSISTANT);
        Response::display('admin/add_user.html');
    }

    /**
     * 添加二级合伙人
     */
    public function add_second_dealer() {
        $parent_id = Request::getParam('id', 0);
        $query_string = Request::getParam('query_string', '');

        if (!$parent_id) {
            return '没有选择父级合伙人!';
        }
        // 获取父级合伙人的信息
        $parent_dealer_info = _uri('user', $parent_id);

        /**
         * 获取助理列表 (@todo 多个合伙人是否允许共用同一个助理?)
         */
        // 助理id是21
        $user_ids = array();
        $user_ids = user_helper::get_role_user_ids(21);
        if ($user_ids) {
            foreach ($user_ids as $k => $v) {
                $user_ids[$k] = user_helper::get_user_info($v);
            }
        }

        Response::assign('assistant_list', $user_ids);
        Response::assign('query_string', $query_string);
        Response::assign('parent_dealer_info', $parent_dealer_info);
        Response::display('admin/add_second_dealer.html');
    }

    /**
     * 查看用户
     */
    public function edit() {
        $id = Request::getParam('id', 0);
        $search_filter = Request::getParam('search_filter', array());
        $status = Request::getParam('status', 1);
        $is_advenced = Request::getParam('is_advenced', 1);
        $page_no = Request::getParam('page_no', 1);
        $dealer_level = Request::getParam('dealer_level', 0);
        $only_dealer = Request::getParam('only_dealer', 0);
        $query_string = Request::getParam('query_string', '');

        if (!$id) {
            return '参数错误！';
        }
        $user_info = _uri('user', $id);
        if (!$user_info) {
            return '对不起，您要查看的信息不存在';
        }

        // 如果存在父级合伙人,则获取父级合伙人的用户名
        if ($user_info['parent_id'] > 0) {
            $parent_user_info = _uri('user', $user_info['parent_id']);
            if ($parent_user_info) {
                $user_info['parent_user_name'] = $parent_user_info['user_name'];
            }
        }

        $PARENT_AGENCY_LIST = user_helper::get_dealers_level_info(1);

        $role_id = user_helper::get_user_role_id($id);

        if ($role_id == user_config::AGENCY) {

            // 获取合伙人的默认仓库地址
            $default_dealer_address = _uri('dealer_address', array('user_id' => $id, 'status' => 1, 'is_default' => 1));
            if ($default_dealer_address) {
                if ('000000' != $default_dealer_address['county_code']) {
                    $user_info['area_code'] = $default_dealer_address['county_code'];
                } elseif ('000000' != $default_dealer_address['city_code']) {
                    $user_info['area_code'] = $default_dealer_address['county_code'];
                } elseif ('000000' != $default_dealer_address['province_code']) {
                    $user_info['area_code'] = $default_dealer_address['county_code'];
                } else {
                    $user_info['area_code'] = '000000';
                }
                $user_info['dealer_address'] = $default_dealer_address['dealer_address'];
                Response::assign('dealer_address_id', $default_dealer_address['id']);
            }/*  else {
                // 如果没有默认仓库地址则创建到关系表中
                $create_dealer_address_id = user_helper::create_dealer_address($user_info['area_code'], $user_info['store_house'], $user_info['id'], 1);
                Response::assign('dealer_address_id', $create_dealer_address_id);
            } */

            $area_code = $user_info['area_code'];
            $area = array();
            if ('000000' != $area_code) {
                $area = _widget('area')->get_area_info_by_area_code($area_code);
                Response::assign('area', $area);
            }

            $store_info = _uri('store', array('user_id' => $id));
            if ($store_info) {
                Response::assign('is_old', $store_info['is_old']);
            } else {
                Response::assign('is_old', 0);
            }

            // 获取合伙人门店信息
            $user_store_info = _uri('user_store', array('user_id' => $id));
            if ($user_store_info) {
                Response::assign('user_store_info', $user_store_info);
            }

        }

        /**
         * 获取助理列表
         * 去掉助理关联 by pjan
         */
        // 助理id是21
        //        $user_ids = array();
        //        $user_ids = user_helper::get_role_user_ids(user_config::ASSISTANT);
        //        if ($user_ids) {
        //            foreach ($user_ids as $k => $v) {
        //                $user_ids[$k] = user_helper::get_user_info($v);
        //            }
        //        }

        /*
         * 获取大区经理列表
         * 去掉大区经理关联 by pjan
         * */
        //        $area_managers = user_helper::get_role_user_ids(user_config::AREA_MANAGER);
        //        if ($area_managers) {
        //            foreach ($area_managers as $k => $v) {
        //                $area_managers[$k] = user_helper::get_user_info($v);
        //            }
        //        }

        //        Response::assign('assistant_list', $user_ids);
        //        Response::assign('area_manager_list', $area_managers);
        Response::assign('is_advenced', $is_advenced);
        Response::assign('search_filter', $search_filter);
        Response::assign('status', $status);
        Response::assign('page_no', $page_no);
        Response::assign('dealer_level', $dealer_level);
        Response::assign('only_dealer', $only_dealer);
        Response::assign('query_string', $query_string);
        Response::assign('PARENT_AGENCY_LIST', $PARENT_AGENCY_LIST);
        Response::assign('role_id', $role_id);
        Response::assign('user_info', $user_info);
        Response::display('admin/view.html');
    }

    /**
     * 设置合伙人地区
     */
    public function edit_area() {
        $id = Request::getParam('user_id', 0);
        $dealer_area_id = Request::getParam('id', 0);
        if (!$id) {
            return '参数错误!';
        }
        $user_info = _uri('user', $id);
        $role_user_info = _uri('role_user', array('user_id' => $id));
        if ($role_user_info['role_id'] != user_config::AGENCY) {
            return '只有合伙人才能是指地区!';
        }

        // 根据合伙人id获取地区信息
        $dealer_area_info = _uri('dealer_area', array('user_id' => $id, 'id' => $dealer_area_id));

        $area = array();
        // 获取省市区的名称
        $province_info = _uri('region', array('area_code' => $dealer_area_info['province_code']));
        $area['province']['area_code'] = $province_info['area_code'];
        $area['province']['area'] = $province_info['area'];
        if ($dealer_area_info['city_code'] != '000000') {
            $city_info = _uri('region', array('area_code' => $dealer_area_info['city_code']));

            if ($city_info) {
                $area['city']['area_code'] = $city_info['area_code'];
                $area['city']['area'] = $city_info['area'];
                $county_info = _uri('region', array('area_code' => $dealer_area_info['county_code']));
                if ($county_info) {
                    $area['county']['area_code'] = $county_info['area_code'];
                    $area['county']['area'] = $county_info['area'];
                }
            }

        } else {
            $area['city']['area_code'] = '';
            $area['city']['area'] = '';
            $area['county']['area_code'] = '';
            $area['county']['area'] = '';
        }

        Response::assign('area', $area);
        Response::assign('user_info', $user_info);
        Response::assign('dealer_area_info', $dealer_area_info);
        Response::assign('id', $id);
        Response::assign('dealer_area_id', $dealer_area_id);
        Response::display("admin/edit_area.html");


    }

    /**
     * 设置合伙人地区
     */
    public function edit_dealer_address() {
        $id = Request::getParam('user_id', 0);
        $dealer_address_id = Request::getParam('id', 0);

        if (!$id) {
            return '参数错误!';
        }

        $user_info = _uri('user', $id);
        $role_user_info = _uri('role_user', array('user_id' => $id));
        if ($role_user_info['role_id'] != user_config::AGENCY) {
            return '只有合伙人才能是指地区!';
        }

        // 根据合伙人id获取地区信息
        $dealer_address_info = _uri('dealer_address', array('user_id' => $id, 'id' => $dealer_address_id));

        $area = array();
        // 获取省市区的名称
        $province_info = _uri('region', array('area_code' => $dealer_address_info['province_code']));
        if ($province_info) {
            $area['province']['area_code'] = $province_info['area_code'];
            $area['province']['area'] = $province_info['area'];
        } else {
            $area['province']['area_code'] = '000000';
            $area['province']['area'] = '';
        }

        if ($dealer_address_info['city_code'] != '000000') {
            $city_info = _uri('region', array('area_code' => $dealer_address_info['city_code']));

            if ($city_info) {
                $area['city']['area_code'] = $city_info['area_code'];
                $area['city']['area'] = $city_info['area'];
                $county_info = _uri('region', array('area_code' => $dealer_address_info['county_code']));
                if ($county_info) {
                    $area['county']['area_code'] = $county_info['area_code'];
                    $area['county']['area'] = $county_info['area'];
                }
            }

        } else {
            $area['city']['area_code'] = '000000';
            $area['city']['area'] = '';
            $area['county']['area_code'] = '000000';
            $area['county']['area'] = '';
        }

        Response::assign('area', $area);
        Response::assign('user_info', $user_info);
        Response::assign('dealer_address_info', $dealer_address_info);
        Response::assign('id', $id);
        Response::assign('dealer_address_id', $dealer_address_id);
        Response::display("admin/edit_dealer_address.html");


    }

    /**
     * 更新合伙人地区信息
     */
    public function update_area() {
        $id = Request::getParam('id', 0);
        $dealer_area_id = Request::getParam('dealer_area_id', 0);
        $province_code = Request::getParam('province', '000000');
        $city_code = Request::getParam('city', '000000');
        $county_code = Request::getParam('county', '000000');
        $detail_address = Request::getParam('detail', '');

        $dealer_area_info = array();
        $dealer_area_info['user_id'] = $id;
        $dealer_area_info['province_code'] = $province_code;
        $dealer_area_info['city_code'] = $city_code;
        $dealer_area_info['county_code'] = $county_code;
        $dealer_area_info['detail_address'] = $detail_address;

        // 更新之前先判断此地区信息是否存在
        $res = _uri('dealer_area', $dealer_area_info);

        if ($res && $res['id'] != $dealer_area_id) {
            return array('此地区信息已经存在了!', 'error', AnUrl('user/admin/show_area_list.html?id=' . $id));
        }

        $dealer_area_info['update_time'] = date('Y-m-d H:i:s');

        $affected_row = _model('dealer_area')->update(array('id' => $dealer_area_id), $dealer_area_info);
        if (!$affected_row) {
            return array('更新失败!', 'error', AnUrl('user/admin/show_area_list.html?id=' . $id));
        }

        Response::assign('status', 1);
        Response::assign('id', $id);
        Response::redirect('user/admin/show_area_list.html?status=1&id=' . $id);

    }

    /**
     * 更新合伙人仓库地址信息
     */
    public function update_dealer_address() {
        $id = Request::getParam('id', 0);
        $dealer_address_id = Request::getParam('dealer_address_id', 0);
        $province_code = Request::getParam('province', '000000');
        $city_code = Request::getParam('city', '000000');
        $county_code = Request::getParam('county', '000000');
        $dealer_address = Request::getParam('dealer_address', '');
        $dealer_name = Request::getParam('dealer_name', '');
        $dealer_mobile = Request::getParam('dealer_mobile', '');
        $is_default = Request::getParam('is_default', '');


        $dealer_address_info = array();
        $dealer_address_info['user_id'] = $id;
        $dealer_address_info['province_code'] = $province_code;
        $dealer_address_info['city_code'] = $city_code;
        $dealer_address_info['county_code'] = $county_code;
        $dealer_address_info['dealer_address'] = $dealer_address;


        // 更新之前先判断此地区信息是否存在
        $res = _uri('dealer_address', $dealer_address_info);
        if ($res && $res['id'] != $dealer_address_id) {
            return array('此地区信息已经存在了!', 'error', AnUrl('user/admin/show_dealer_address_list.html?id=' . $id));
        }

        ts_helper::begin();
        try {

            // 只能有一个默认仓库
            if ($is_default) {
                ts_helper::_model('dealer_address')->update(array('user_id' => $id), array('is_default' => 0));
                $dealer_address_info['is_default'] = 1;
            }

            $dealer_address_info['update_time'] = date('Y-m-d H:i:s');
            $dealer_address_info['dealer_name'] = $dealer_name;
            $dealer_address_info['dealer_mobile'] = $dealer_mobile;

            ts_helper::_model('dealer_address')->update($dealer_address_id, $dealer_address_info);
            ts_helper::_model('dealer_address')->commit();

        } catch (Exception $e) {
            ts_helper::trace_log($e);
            ts_helper::rollback();
            return array('更新地址失败!', 'error', AnUrl('user/admin/show_dealer_address_list.html?id=' . $id));
        }

        Response::assign('status', 1);
        Response::assign('id', $id);
        Response::redirect('user/admin/show_dealer_address_list.html?status=1&id=' . $id);

    }


    /**
     * 检测合伙人地区是否存在
     */
    public function check_area_exists() {
        $id = Request::getParam('id', 0);
        $dealer_area_id = Request::getParam('dealer_area_id', 0);
        $province_code = Request::getParam('province_code', '000000');
        $city_code = Request::getParam('city_code', '000000');
        $county_code = Request::getParam('county_code', '000000');
        $detail_address = Request::getParam('detail_address', '');

        if (!$province_code) {
            $province_code = '000000';
        }
        if (!$city_code) {
            $city_code = '000000';
        }
        if (!$county_code) {
            $county_code = '000000';
        }


        $dealer_area_info = array();
        $dealer_area_info['id'] = $dealer_area_id;
        $dealer_area_info['user_id'] = $id;
        $dealer_area_info['province_code'] = $province_code;
        $dealer_area_info['city_code'] = $city_code;
        $dealer_area_info['county_code'] = $county_code;
        $dealer_area_info['detail_address'] = $detail_address;

        $res = _uri('dealer_area', $dealer_area_info);
        if ($res) {
            if ($res['id'] == $dealer_area_id) {
                echo 'same';
            } else {
                echo 'no';
            }
        } else {
            echo 'ok';
        }
    }

    /**
     * 检测合伙人仓库地址是否存在
     */
    public function check_dealer_address_exists() {
        $id = Request::getParam('id', 0);
        $dealer_address_id = Request::getParam('dealer_address_id', 0);
        $province_code = Request::getParam('province_code', '000000');
        $city_code = Request::getParam('city_code', '000000');
        $county_code = Request::getParam('county_code', '000000');
        $dealer_address = Request::getParam('dealer_address', '');

        if (!$province_code) {
            $province_code = '000000';
        }
        if (!$city_code) {
            $city_code = '000000';
        }
        if (!$county_code) {
            $county_code = '000000';
        }

        $dealer_area_info = array();
        $dealer_area_info['id'] = $dealer_address_id;
        $dealer_area_info['user_id'] = $id;
        $dealer_area_info['province_code'] = $province_code;
        $dealer_area_info['city_code'] = $city_code;
        $dealer_area_info['county_code'] = $county_code;
        $dealer_area_info['dealer_address'] = $dealer_address;

        $res = _uri('dealer_address', $dealer_area_info);
        if ($res) {
            if ($res['id'] == $dealer_address_id) {
                echo 'same';
            } else {
                echo 'no';
            }
        } else {
            echo 'ok';
        }
    }


    /**
     * 检测父级合伙人是否存在
     */
    public function check_parent_dealer_exist() {
        $parent_user_name = Request::getParam('parent_user_name', '');
        if (!$parent_user_name) {
            echo 'no';
        }

        $parent_user_info = _uri('user', array('user_name' => $parent_user_name));

        if ($parent_user_info) {
            echo 'ok';
        } else {
            echo 'no';
        }

    }


    /**
     * 获取一级合伙人的子合伙人列表
     */
    public function get_second_dealer_list() {
        $id = Request::getParam('id', '0');
        if ($id == 0) {
            echo 'no';
            return;
        }

        $second_dealer_list = _model('user')->getList(array('parent_id' => $id));
        if ($second_dealer_list) {
            echo json_encode((object)$second_dealer_list);
        } else {
            echo 'no';
        }
    }

    /**
     * 查看经销地区
     */
    public function show_area_list() {
        $id = Request::getParam('id', 0);
        $page_no = Request::getParam('page_no', 1);

        $filter = array();
        $filter['user_id'] = $id;
        $status = Request::getParam('status', 1);
        $filter['status'] = $status;

        // 获取此合伙人合伙人的地区信息
        $area_list = get_data_list('dealer_area', $filter, 'ORDER BY `province_code`,`city_code`,`county_code`', $page_no, 20);

        if ($area_list) {
            foreach ($area_list as $k => $v) {
                // 通过地区代码获取地区名称
                $province_info = _uri('region', array('area_code' => $v['province_code']));
                $province_name = $province_info['area'];
                $city_info = _uri('region', array('area_code' => $v['city_code']));
                if ($city_info) {
                    $city_name = $city_info['area'];
                    $area_list[$k]['city_name'] = $city_name;
                    $county_info = _uri('region', array('area_code' => $v['county_code']));
                    if ($county_info) {
                        $county_name = $county_info['area'];
                        $area_list[$k]['county_name'] = $county_name;
                    }
                }

                $area_list[$k]['province_name'] = $province_name;

            }
        }

        // 获取用户名
        $user_info = _uri('user', $id);

        Response::assign('status', $status);
        Response::assign('area_list', $area_list);
        Response::assign('user_info', $user_info);
        Response::assign('id', $id);
        Response::display('admin/show_area_list.html');
    }

    /**
     * 查看合伙人仓库地址
     */
    public function show_dealer_address_list() {
        $id = Request::getParam('id', 0);
        $page_no = Request::getParam('page_no', 1);
        $query_string = Request::getParam('query_string', '');

        $filter = array();
        $filter['user_id'] = $id;

        $status = Request::getParam('status', 1);
        $filter['status'] = $status;

        $user_info = user_helper::get_user_info($id);
        if (!$user_info) {
            Response::redirect('user/admin');
        }

        $dealer_address_list = dealers_helper::get_dealer_address_list($id, $page_no, 20);

        Response::assign('status', $status);
        Response::assign('page_no', $page_no);
        Response::assign('dealer_address_list', $dealer_address_list);
        Response::assign('user_info', $user_info);
        Response::assign('id', $id);
        Response::assign('query_string', $query_string);
        Response::display('admin/show_dealer_address_list.html');
    }


    /**
     * 添加合伙人地区
     */
    public function create_area() {
        $id = Request::getParam('id', 0);
        $province_code = Request::getParam('province', '000000');
        $city_code = Request::getParam('city', '000000');
        $county_code = Request::getParam('county', '000000');
        $detail_address = Request::getParam('detail', '');

        $dealer_area_info = array();
        $dealer_area_info['province_code'] = $province_code;
        $dealer_area_info['city_code'] = $city_code;
        $dealer_area_info['county_code'] = $county_code;
        $dealer_area_info['user_id'] = $id;
        $dealer_area_info['detail_address'] = $detail_address;

        $area_info = _uri('dealer_area', $dealer_area_info);
        if ($area_info) {
            return array('此地区信息已经存在了!', 'error', AnUrl('user/admin/show_area_list.html?id=' . $id));
        }

        $dealer_area_info['add_time'] = date('Y-m-d H:i:s');
        $dealer_area_info['update_time'] = date('Y-m-d H:i:s');

        $res = _model('dealer_area')->create($dealer_area_info);

        Response::redirect('user/admin/show_area_list.html?id=' . $id);

    }


    /**
     * 添加合伙人地区
     */
    public function create_dealer_address() {
        $id = Request::getParam('id', 0);
        $province_code = Request::getParam('province', '000000');
        $city_code = Request::getParam('city', '000000');
        $county_code = Request::getParam('county', '000000');
        $dealer_address = Request::getParam('dealer_address', '');
        $dealer_name = Request::getParam('dealer_name', '');
        $dealer_mobile = Request::getParam('dealer_mobile', '');
        $is_default = Request::getParam('is_default', '');
        $query_string = Request::getParam('query_string', '');

        $dealer_address_info = array();
        $dealer_address_info['province_code'] = $province_code;
        $dealer_address_info['city_code'] = $city_code;
        $dealer_address_info['county_code'] = $county_code;
        $dealer_address_info['user_id'] = $id;
        $dealer_address_info['dealer_address'] = $dealer_address;

        $address_info = _uri('dealer_address', $dealer_address_info);
        if ($address_info) {
            return array(
                '此地区信息已经存在了!',
                'error',
                AnUrl('user/admin/show_dealer_address_list.html?id=' . $id . '&query_string=' . $query_string)
            );
        }

        ts_helper::begin();
        try {

            // 只能有一个默认仓库
            if ($is_default) {
                ts_helper::_model('dealer_address')->update(array('user_id' => $id), array('is_default' => 0));
                $dealer_address_info['is_default'] = 1;
            }

            $dealer_address_info['dealer_name'] = $dealer_name;
            $dealer_address_info['dealer_mobile'] = $dealer_mobile;

            $dealer_address_info['add_time'] = date('Y-m-d H:i:s');
            $dealer_address_info['update_time'] = date('Y-m-d H:i:s');

            ts_helper::_model('dealer_address')->create($dealer_address_info);
            ts_helper::_model('dealer_address')->commit();

        } catch (Exception $e) {
            ts_helper::trace_log($e);
            ts_helper::rollback();
            return array(
                '添加地址失败!',
                'error',
                AnUrl('user/admin/show_dealer_address_list.html?id=' . $id . '&query_string=' . $query_string)
            );
        }

        Response::redirect('user/admin/show_dealer_address_list.html?id=' . $id . '&query_string=' . $query_string);

    }

    /**
     * 为合伙人添加地区
     */
    public function add_dealer_area() {
        $id = Request::getParam('id', 0);

        // 根据用户id获取用户信息
        $user_info = _uri('user', $id);

        Response::assign('user_info', $user_info);
        Response::assign('id', $id);
        Response::display('admin/add_dealer_area.html');
    }

    /**
     * 为合伙人添加仓库地址
     */
    public function add_dealer_address() {
        $id = Request::getParam('id', 0);
        $query_string = Request::getParam('query_string', '');

        // 根据用户id获取用户信息
        $user_info = _uri('user', $id);

        Response::assign('user_info', $user_info);
        Response::assign('query_string', $query_string);
        Response::assign('id', $id);
        Response::display('admin/add_dealer_address.html');
    }


    /**
     * 新建用户
     */
    public function create() {
        $info = Request::getParam('info', array());
        $is_old = Request::getParam('is_old', 0);

        // 有父级id说明要添加的是二级合伙人
        if (isset($info['parent_id']) && $info['parent_id'] > 0) {
            $info['role_id'] = user_config::AGENCY;
        }

        $hash = user_helper::random_hash(6);
        $role_id = $info['role_id'];
        $password = $info['password'];
        $addon_price = Request::getParam('addon_price', 0.00);

        if (user_helper::is_pwd_null($password)) {
            return array('密码内不能包含空字符！', 'error', AnUrl('user/admin'));
        } else {
            if (!user_helper::is_strlen_scope($password, 6)) {
                return array('密码长度不符合要求！', 'error', AnUrl('user/admin'));
            }
            $info['password'] = user_helper::md5_password(trim($password), $hash);
        }

        //去除roleid
        unset($info['role_id']);

        if ($info['email']) {
            if (!filter_var($info['email'], FILTER_VALIDATE_EMAIL)) {
                return array('邮箱格式不正确！', 'error', AnUrl('user/admin'));
            }
        }

        if ($info['mobile']) {
            if (trim($info['mobile']) == '') {
                return array('手机号不能为空！', 'error', AnUrl('user/admin'));
            }
            if (!$info['user_name']) {
                $info['user_name'] = $info['mobile'];
            }
        }

        //判断用户信息是否唯一
        $unique_info = user_helper::user_info_unique($info['user_name'], $info['email'], $info['mobile']);
        if ($unique_info['info'] == 'error') {
            return array($unique_info['msg'], 'error', AnUrl('user/admin'));
        }

        // 判断如果是合伙人,判断合伙人等级
        if ($role_id == user_config::AGENCY) {
            if (0 == @$info['parent_id'] || !isset($info['parent_id'])) {
                $info['dealer_level'] = 1;
            } else {
                $info['dealer_level'] = 2;
            }

        } else {
            $info['dealer_level'] = 0;
            $info['parent_id'] = 0;

            // 不是合伙人,删掉多余数据
            unset($info['bank_name']);
            unset($info['bank_code']);
            unset($info['store_house']);
        }

        $info['hash'] = $hash;

        $user_id = _model('user')->create($info);

        if ($user_id) {
            _model('role_user')->create(array('user_id' => $user_id, 'role_id' => $role_id));
            // 如果是合伙人 需要创建店铺
            if ($role_id == user_config::AGENCY) {
                $store_info = array(
                    'user_id' => $user_id,
                    //'name'=>$info['user_name'],
                    //'mobile'=>$info['mobile'],
                    'is_old' => $is_old,
                    'owner_id' => $user_id,
                    'title' => $info['user_name'] . '合伙人门店'
                );

                _model('store')->create($store_info);
                $user_store_info = array(
                    'user_id' => $user_id,
                    'addon_price' => $addon_price
                );

                // 处理合伙人的身份证正反面,和合同图片
                foreach ($_FILES as $k => $v) {
                    if ($v['error'] == 0) {
                        $image_info = aliysso_helper::upload_file($v, false);
                        if ($image_info) {
                            $user_store_info[$k] = $image_info['file_path'];
                        }
                    }
                }
                _model('user_store')->create($user_store_info);

            }

            // 合伙人注册发送短信
            if ($role_id == user_config::AGENCY) {
                aliysms_helper::sms_send('抱抱堂', array(
                    'name' => $info['realname'],
                    'user_name' => $info['user_name'],
                    'code' => $password
                ), $info['mobile'], 'add_dealer');
                return array(
                    '创建合伙人成功，点击添加仓库地址!',
                    'success',
                    AnUrl('user/admin/show_dealer_address_list.html?id=' . $user_id)
                );
            }

            Response::redirect(AnUrl('user/admin'));
        } else {
            return array('添加失败，请重新添加！', 'error', AnUrl('user/admin'));
        }
    }

    /**
     * 更新用户
     */
    public function update() {
        $info = Request::getParam('info', array());
        $is_old = Request::getParam('is_old', 0);
        $query_string = Request::getParam('query_string', '');

        $query_string = base64_decode($query_string);

        $user_id = $info['id'];
        $hash = user_helper::user_hash($user_id);

        if ($info['password']) {
            if (user_helper::is_pwd_null($info['password'])) {
                return array('密码内不能包含空字符！', 'error', AnUrl('user/admin?' . $query_string));
            } else {
                if (!user_helper::is_strlen_scope($info['password'], 6)) {
                    return array('密码长度不符合要求！', 'error', AnUrl('user/admin?' . $query_string));
                }
                $info['password'] = user_helper::md5_password(trim($info['password']), $hash);
            }
        } else {
            unset($info['password']);
        }

        //判断用户信息是否唯一
        if (!user_helper::is_username_unique($info['mobile'], $user_id)) {
            // 判断用户角色是分店店长
            $role_id = user_helper::get_user_role_id($user_id);
            $mobile_user_info = _uri('user', array('mobile' => $info['mobile']));
            $mobile_role_id = user_helper::get_user_role_id($mobile_user_info['id']);
            // 不是店长且通过手机号查询到的用户角色也不是店长,则不允许重复
            if (($mobile_role_id != user_config::STORE_MANAGER && $mobile_role_id != user_config::STORE_OWNER) &&
                ($role_id != user_config::STORE_MANAGER && $role_id != user_config::STORE_OWNER)
            ) {
                return array('当前手机号已被注册，不能重复注册！', 'error', AnUrl('user/admin?' . $query_string));
            }
        }

        if (!user_helper::is_email_unique($info['email'], $user_id)) {
            return array('当前邮箱已被注册，不能重复注册！', 'error', AnUrl('user/admin?' . $query_string));
        }

        // 获取用户角色信息
        $role_user_info = _uri('role_user', array('user_id' => $user_id));
        // 获取用户信息
        $user_info = _uri('user', $user_id);

        // 判断如果是合伙人,判断合伙人等级
        if ($role_user_info['role_id'] == user_config::AGENCY) {

            if ($info['dealer_level'] == 2) {
                $parent_agency_info = _uri('user', array('id' => $info['parent_id'], 'dealer_level' => 1));
                if (!$parent_agency_info) {
                    return array('父级合伙人不存在！', 'error', AnUrl('user/admin?' . $query_string));;
                } else {
                    $info['parent_id'] = $parent_agency_info['id'];
                }
            } else {
                $info['parent_id'] = 0;
            }

            // 更新合伙人门店是否是老店铺
            _model('store')->update(array('user_id' => $user_id), array('is_old' => $is_old));

            // 处理合伙人的身份证正反面,和合同图片
            $user_store_info = array();
            foreach ($_FILES as $k => $v) {
                if ($v['error'] == 0) {
                    $image_info = aliysso_helper::upload_file($v, false);
                    if ($image_info) {
                        $user_store_info[$k] = $image_info['file_path'];
                    }
                } else {
                    $user_store = _uri('user_store', array('user_id' => $user_id));
                    if ($user_store) {
                        $user_store_info[$k] = $user_store[$k];
                    }
                }
            }
            _model('user_store')->update(array('user_id' => $user_id), $user_store_info);

            // 是否打开抱抱币
            if ($info['is_bbcoin_enable']) {
                bbcoin_helper::open_bbcoin_limit($user_id);
            }

        } else {
            $info['dealer_level'] = 0;
            $info['parent_id'] = 0;

            // 不是合伙人,删掉多余数据
            unset($info['bank_name']);
            unset($info['bank_code']);
            unset($info['dealer_address']);
        }

        $affected = _model('user')->update($user_id, $info);

        if ($user_id) {
            if ($user_info['mobile'] != $info['mobile']) {
                // 发送一条新的用户名和密码的短信 @TODO
            }
            Response::redirect(AnUrl('user/admin?' . $query_string));
        } else {
            return array('修改失败，请重新添加！', 'error', AnUrl('user/admin?' . $query_string));
        }
    }

    /**
     * 禁用合伙人地区
     */
    public function delete_dealer_area() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $dealer_area_info = _uri('dealer_area', (int)$v);
            if (!$dealer_area_info) {
                continue;
            }

            if (1 == $dealer_area_info['status']) {
                _model('dealer_area')->update($v, array('status' => 0));
            }
        }

        return 'ok';
    }

    /**
     * 禁用合伙人仓库地址
     */
    public function delete_dealer_address() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $dealer_address_info = _uri('dealer_address', (int)$v);
            if (!$dealer_address_info) {
                continue;
            }

            if (1 == $dealer_address_info['status']) {
                _model('dealer_address')->update($v, array('status' => 0, 'is_default' => 0));
            }
        }

        return 'ok';
    }

    /**
     * 禁用
     * @return array
     */
    public function delete() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $user_info = _uri('user', (int)$v);
            if (!$user_info) {
                continue;
            }

            if (1 == $user_info['status']) {
                _model('user')->update($v, array('status' => 0));
            }
        }

        return 'ok';
    }

    /**
     * 更新地区状态
     * @return array
     */
    public function change_dealer_area_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $dealer_area_info = _uri('dealer_area', $id);
        if ($status == $dealer_area_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('dealer_area')->update($id, array('status' => 1));
        }

        return 'ok';
    }


    /**
     * 更新合伙人仓库地址状态
     * @return array
     */
    public function change_dealer_address_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $dealer_address_info = _uri('dealer_address', $id);
        if ($status == $dealer_address_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('dealer_address')->update($id, array('status' => 1));
        }

        return 'ok';
    }


    /**
     * 更新状态
     * @return array
     */
    public function change_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $user_info = _uri('user', $id);
        if ($status == $user_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('user')->update($id, array('status' => 1));
        }

        return 'ok';
    }

    /**
     * 显示修改密码
     */
    public function password() {
        $id = user_helper::get_user_id();

        Response::assign('id', $id);

        Response::display('admin/password.html');
    }

    /**
     * 保存密码
     */
    public function pass_save() {
        $id = Request::getParam('id', 0);
        $old = Request::getParam('oldpassword', '');
        $new = Request::getParam('password', '');
        $re = Request::getParam('repassword', '');

        if ($id != user_helper::get_user_id()) {
            return '登录超时！';
        }
        $user_info = _uri('user', $id);

        if (user_helper::md5_password($old, $user_info['hash']) != $user_info['password']) {
            return '原始密码不正确';
        }

        if (!$new && !$re && $new != $re) {
            return '输入正确的密码';
        }

        if (user_helper::is_pwd_null($new)) {
            return '密码中不能含有空字符！';
        }
        if (!user_helper::is_strlen_scope($new, 6)) {
            return array('密码长度不符合要求！', 'error', AnUrl('user/admin'));
        }
        $affected = _model('user')->update($id, array('password' => user_helper::md5_password($new, $user_info['hash'])));
        Response::redirect(AnUrl('admin'));
    }


    /**
     * 模糊匹配手机号
     */
    public function get_store_mobile() {
        $admin_user_role_id = user_helper::get_admin_role_id();
        // 当前登录账号下的合伙人列表
        $dealer_ids = user_helper::get_assistant_dealer_ids();

        $term = an_request('term', '');
        $data = array();

        if ($term) {

            $filter['mobile LIKE'] = $term . '%';
            $filter['dealer_level > '] = 0;
            $filter['status'] = 1;

            $list = _model('user')->getList($filter, 'limit 8');
            if ($list) {
                foreach ($list as $k => $v) {
                    // 助理只允许显示自己的合伙人，管理员不限制
                    if (in_array($v['id'], $dealer_ids) || $admin_user_role_id == user_config::ADMIN) {
                        $data[$k]['label'] = $v['mobile'];
                        $data[$k]['value'] = $v['mobile'];
                        $data[$k]['link'] = '';
                    }
                }
            }
        }

        if (!$data) {
            $data[0]['label'] = '暂无记录';
            $data[0]['value'] = '';
            $data[0]['link'] = '';
        }

        echo json_encode($data);
        exit;
    }
}

?>
